import asyncio
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.config import settings
from app.database import init_db
from app.services.price_service import price_service
from app.services.scheduler_service import scheduler_service
from app.services.websocket_manager import websocket_manager
from app.routers import users, contracts, prices, websocket

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    # Startup
    logger.info("Starting Event Contract Platform...")
    
    # Initialize database
    await init_db()
    logger.info("Database initialized")
    
    # Setup price service callback for WebSocket broadcasting
    async def price_callback(price_data):
        await websocket_manager.broadcast_price_update(
            price_data.symbol,
            price_data.price,
            price_data.timestamp
        )
    
    price_service.add_price_callback(price_callback)
    
    # Start services
    await price_service.start()
    await scheduler_service.start()
    
    logger.info("All services started successfully")
    
    yield
    
    # Shutdown
    logger.info("Shutting down Event Contract Platform...")
    await price_service.stop()
    await scheduler_service.stop()
    logger.info("All services stopped")


# Create FastAPI app
app = FastAPI(
    title="Event Contract Platform",
    description="Cryptocurrency price prediction event contract platform",
    version="1.0.0",
    lifespan=lifespan
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify allowed origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(users.router)
app.include_router(contracts.router)
app.include_router(prices.router)
app.include_router(websocket.router)


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "message": "Event Contract Platform API",
        "version": "1.0.0",
        "supported_symbols": settings.symbols_list
    }


@app.get("/health")
async def health_check():
    """Health check endpoint"""
    latest_prices = price_service.get_all_latest_prices()
    
    return {
        "status": "healthy",
        "price_service": "running" if price_service.running else "stopped",
        "scheduler_service": "running" if scheduler_service.running else "stopped",
        "active_connections": len(websocket_manager.active_connections),
        "latest_prices": {
            symbol: {
                "price": price_data.price,
                "timestamp": price_data.timestamp
            }
            for symbol, price_data in latest_prices.items()
        }
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug
    )
